package com.ybServer.service.impl;

import com.ybServer.dao.FeedbackDAO;
import com.ybServer.dao.UserDAO;
import com.ybServer.model.User;
import com.ybServer.service.UserService;
import com.ybServer.util.Constant;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource
    private UserDAO userDao;

    @Resource
    private FeedbackDAO feedbackDAO;

    public User[] selectUserByName(String name) {
        return this.userDao.selectUserByName(name);
    }

    @Override
    public boolean userExists(User user) throws Exception {
        return false;
    }

    @Override
    public void userRegister(User user) throws Exception {
        userDao.register(user);

    }

    @Override
    public User userLogin(User user) throws Exception {
        // TODO Auto-generated method stub

        return userDao.queryUser(user);
    }

    @Override
    public void updateUserPwd(User user) throws Exception {
        // TODO Auto-generated method stub
        userDao.updateUserPwd(user);
    }

    @Override
    public User getUserBasicInfoById(long id) throws Exception {
        // TODO Auto-generated method stub
        return userDao.queryUserBasicInfoByID(id);
    }

    @Override
    public void updateUserInfo(User user) throws Exception {
        // TODO Auto-generated method stub
        userDao.updateUserInfo(user);
    }

    @Override
    public byte[] getUserIconByUserId(String UserId) throws Exception {
        File file = new File(Constant.STORAGE_PATH + Constant.USER_ICON_PATH + UserId + ".jpeg");
        FileInputStream inputStream = new FileInputStream(file);
        int i = inputStream.available();
        byte[] buff = new byte[i];
        inputStream.read(buff);
        inputStream.close();
        return buff;
    }

    @Override
    public void addFeedback(String uname, String phone, String content) throws Exception {
        feedbackDAO.addFeedback(uname, phone, content);
    }

    @Override
    public void updateUserIcon(MultipartFile icon) throws Exception {
        /**上传得到的文件名 */
        String fileName = icon.getOriginalFilename();

        /**创建文件的虚拟路径*/
        String virtualPath = Constant.STORAGE_PATH + Constant.USER_ICON_PATH + fileName;
        File saveFile = new File(virtualPath);
        if (saveFile.exists())
            saveFile.delete();
        icon.transferTo(saveFile);
    }
}
